
#include "hnvs.h"
#include <string.h>


static const char *default_ssid = "LANSI";
static const char *default_password = "Lansi1234";
static const char *default_name = "LABEL-NAME";
static const char *default_url = "192.168.0.194:7842";
static const char *default_uuid = "00000000-0000-0000-0000-00000000000";

static const char *nvs_namespace = "hnvs";

static const char *ssid_key = "ssid";
static const char *password_key = "password";
static const char *name_key = "name";
static const char *url_key = "url";
static const char *uuid_key = "uuid";

static void hnvs_write_str(const char *key, const char *value);
static void hnvs_read_str(const char *key, char *value, const char *default_value, uint32_t len);


void hnvs_write_ssid(const char *ssid) {
    hnvs_write_str(ssid_key, ssid);
}
void hnvs_read_ssid(char *ssid) {
    hnvs_read_str(ssid_key, ssid, default_ssid, 32);
}

void hnvs_write_password(const char *password) {
    hnvs_write_str(password_key, password);
}
void hnvs_read_password(char *password) {
    hnvs_read_str(password_key, password, default_password, 64);
}

void hnvs_write_name(const char *name) {
    hnvs_write_str(name_key, name);
}
void hnvs_read_name(char *name) {
    hnvs_read_str(name_key, name, default_name, 64);
}

void hnvs_write_url(const char *url) {
    hnvs_write_str(url_key, url);
}
void hnvs_read_url(char *url) {
    hnvs_read_str(url_key, url, default_url, 64);
}

void hnvs_write_uuid(const char *uuid) {
    hnvs_write_str(uuid_key, uuid);
}
void hnvs_read_uuid(char *uuid) {
    hnvs_read_str(uuid_key, uuid, default_uuid, 64);
}


static void hnvs_write_str(const char *key, const char *value) {
    nvs_handle handle;
    ESP_ERROR_CHECK(nvs_open(nvs_namespace, NVS_READWRITE, &handle));
    ESP_ERROR_CHECK(nvs_set_str(handle, key, value));
    ESP_ERROR_CHECK(nvs_commit(handle));
    nvs_close(handle);
}


static void hnvs_read_str(const char *key, char *value, const char *default_value, uint32_t len) {
    nvs_handle handle;
    uint32_t str_length = len;
    ESP_ERROR_CHECK(nvs_open(nvs_namespace, NVS_READWRITE, &handle));
    if(ESP_OK != nvs_get_str(handle, key, value, &str_length)) {
        HLOGI("hnvs", "%s not found, use default value: %s", key, default_value);
        ESP_ERROR_CHECK(nvs_set_str(handle, key, default_value));
        strcpy(value, default_value);
        ESP_ERROR_CHECK(nvs_commit(handle));
    }
    nvs_close(handle);
}



